<?php

namespace app\admin\model;

use EasyWeChat\Factory;
use think\Env;
use think\Model;

class Assistant extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    public static $app;
    // 追加属性
    protected $append = [
    ];

    public function initialize()
    {
        self::$app = Factory::work(Assistant::config());
    }


    public static function config()
    {

        $config = [
            'agent_id' => Env::get('Assistant.agent_id'),
            'corp_id' => Env::get('user.corp_id'),
            'secret'   => Env::get('Assistant.secret'),
            'response_type' => Env::get('Assistant.response_type'),
            'log' => [
                'level' => Env::get('Assistant.level'),
                'file' => __DIR__.Env::get('Assistant.file'),
            ],
            'oauth'=> [
                'scopes'=> Env::get('Assistant.scopes'),
                'callback' => Env::get('Assistant.callback')
            ]
        ];
        return $config;
    }

    /**
     * 添加一个群成员
     * @param $params
     * @return mixed
     */
    public static function addChat($name,$owner,array $userlist)
    {
        $array= ['name'=>$name,'owner'=>$owner,'userlist'=>$userlist];
        $token = self::$app->access_token->getToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/appchat/create?access_token={$token['access_token']}";
        //参数以json格式传送
        $response = \fast\Http::post($url,json_encode($array));
        return json_decode($response,true);
    }

    /**
     * 修改群聊信息
     * @param $chatid
     * @param null $name
     * @param null $owner
     * @param array|null $add_user_list
     * @param array|null $del_user_list
     * @return mixed
     */
    public static function updateChat($chatid, $name = null, $owner = null, array $add_user_list = null, array $del_user_list = null)
    {
        $array= ['chatid'=>$chatid];
        if ($name) $array['name'] = $name;
        if ($owner) $array['owner'] = $owner;
        if ($add_user_list) $array['add_user_list'] = $add_user_list;
        if ($del_user_list) $array['del_user_list'] = $del_user_list;
        $token = self::$app->access_token->getToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/appchat/update?access_token={$token['access_token']}";
        //参数以json格式传送
        $response = \fast\Http::post($url,json_encode($array));
        return json_decode($response,true);
    }

    /**
     * 消息推送
     * @param $msg
     * @return false|string
     */
    public static function pushChat($msg)
    {
        $token = self::$app->access_token->getToken();//获取企业微信token
        $url = "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token={$token['access_token']}";
        $response = \fast\Http::post($url,$msg);
        return json_decode($response,true);
    }
}
